<template>
  <view class="related-houses-page">
    <!-- 顶部信息区 -->
    <view class="info-section">
      <view class="info-text">
        您在该区域共<text class="highlight">{{ totalHouses }}套房产</text>，
        票权共计<text class="highlight">{{ totalVotes }}票</text>
        ，专有部分面积共计<text class="highlight">{{ totalArea }}m²</text>
      </view>
   
      <view class="warning-text">若面积有误，请联系投票组织方进行变更,</view>
      <view  class="warning-text">
        <black >{{initiator}} ： </black> 
       
        <span class="highlight" @click="callPhone">{{ mobile }}</span>
     </view>
     <view class="tip-text">若有房屋未显示，请先申请房屋绑定。</view>
    </view>

    <!-- 我的房屋列表 -->
    <view class="house-section">
      <view class="section-header">
        <text class="section-title">我的房屋</text>
        <view class="bind-btn" @click="goToBind">
          <text class="bind-text">房屋绑定</text>
        </view>
      </view>

      <view class="house-list">
        <view 
          v-for="house in houseList" 
          :key="house.id"
          class="house-item"
          :class="{ 'missing': house.isMissing && !house.hasVoted, 'voted': house.hasVoted }"
        >
          <view class="house-info">
            <text class="house-name">{{ house.name }}</text>
            <text class="house-area">({{ house.area }}m²)</text>
          </view>
          <view class="house-status">
            <text v-if="house.hasVoted" class="voted-tag">已投票</text>
            <text v-else-if="house.isMissing" class="missing-tag">新增</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-action">
      <view class="action-btn" @click="goToVote">
        去投票
      </view>
    </view>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import { getBindInfo, recordCheck } from '@/api/index'
import ls from '@/util/ls'
import companyInfo from '@/util/companyInfo'

export default {
  name: 'RelatedHouses',
  data() {
    return {
      voteId: '',
      communityId: '',
      houseList: [],
      totalVotes: 1,
      selectedHouses: [],
      allBoundHouses: [], // 所有已绑定的房屋
      passedHouses: [], // 传入的房屋列表
      houseCheckResult: null, // 房屋投票检查结果
      mobile: '',
      initiator:""
    }
  },
  
  computed: {
    ...mapState('community', ['houseBindList']),
    
    // 总房产数
    totalHouses() {
      return this.houseList.length
    },
    
    // 总面积
    totalArea() {
      return this.houseList.reduce((sum, house) => {
        return sum + (parseFloat(house.area) || 0)
      }, 0).toFixed(1)
    }
  },
  
  onLoad(options) {
    if (options.voteId) {
      this.voteId = options.voteId
    }
    if (options.communityId) {
      this.communityId = options.communityId
    }
    if (options.mobile) {
      this.mobile = options.mobile
      this.initiator=options.initiator
    }else{
      this.mobile = companyInfo.phone
      this.initiator = "联系电话"
    }
    uni.setStorageSync('fromRelatedHouses', true)
    // this.init()
  },
  onShow() {
    setTimeout(()=>{
        this.init()
    })
  },
  
  methods: {
    callPhone(){
      uni.makePhoneCall({
        phoneNumber: this.mobile
      })
    },
    async init() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        // 1. 获取用户信息
        const useinfo = ls.get('user')
        const wxUser = useinfo?.wxUser
        
        if (!wxUser || !wxUser.wxUserId) {
          uni.hideLoading()
          uni.$u.toast('用户信息不存在')
          return
        }
        
        // 2. 获取传入的房屋列表（投票页面已选择的）
        const tempHouseList = uni.getStorageSync('tempHouseList')
        this.passedHouses = tempHouseList || []
        
        // 3. 获取所有已绑定的房屋（auditStatus=2表示已绑定）
        const bindData = await getBindInfo({
          communityId: this.communityId,
          liveUserId: wxUser.wxUserId.toString(),
          auditStatus: 2
        })
    //   console.log("bindData",bindData)
       
        this.allBoundHouses = bindData.rows|| []

        console.log("bindData22", this.allBoundHouses)
        
        // 4. 调用 pms/record/check 接口获取投票状态
        await this.checkVoteRecord(wxUser.wxUserId)
        
        this.$nextTick(()=>{
          this.compareAndProcessHouses()
        })
        uni.hideLoading()
      } catch (error) {
        console.error('获取房屋列表失败:', error)
        uni.hideLoading()
        uni.$u.toast('获取房屋列表失败')
      }
    },
    
    // 调用 pms/record/check 接口
    async checkVoteRecord(wxUserId) {
      try {
        // 获取所有已绑定房屋的ID
        const houseIds = this.allBoundHouses.map(item => item.house.houseId).filter(id => id)
        
        if (houseIds.length === 0) {
          console.log('没有房屋，跳过检查')
          return
        }
        
        // 准备接口参数
        const params = {
          voteId: Number(this.voteId),
          communityId: this.communityId,
          liveUserId: wxUserId,
          houseId: houseIds.join(','),
          recordType: 1,
        }
        
        console.log('调用 pms/record/check 接口，参数:', params)
        
        const res = await recordCheck(params)
        
        console.log('pms/record/check 接口响应:', res)
        
        if (res && res.code === 200 && res.data) {
          this.houseCheckResult = {
            successHouse: res.data.successHouse || [],
            failedHouse: res.data.failedHouse || []
          }
          console.log('房屋检查结果:', this.houseCheckResult)
        }
      } catch (error) {
        console.error('检查投票记录失败:', error)
      }
    },
    
    // 对比传入的房屋和已绑定的房屋，找出漏选的
    compareAndProcessHouses() {
      // 将传入的房屋ID转为Set，便于查找
      const passedHouseIds = new Set(
        this.passedHouses.map(h => h.houseId || h.id)
      )
      
      // 获取已投票的房屋ID
      const votedHouseIds = new Set()
      if (this.houseCheckResult && this.houseCheckResult.failedHouse) {
        this.houseCheckResult.failedHouse.forEach(item => {
          if (item.pmsHouse && item.pmsHouse.houseId) {
            votedHouseIds.add(String(item.pmsHouse.houseId))
          }
        })
      }
      console.log('已投票的房屋ID:', Array.from(votedHouseIds))
  
      // 处理所有已绑定的房屋 
      this.houseList = this.allBoundHouses.map(house => {
        console.log("house",house)
        const houseId = house.house.houseId ||""
        const areaInfo = house.house.areaInfo ? house.house.areaInfo.replace(/#/g, '-') : ''
        const roomCode = house.house.roomCode || ''
        
        // 判断是否在传入的列表中
        const isInPassed = passedHouseIds.has(houseId)
        // 漏选的房屋：已绑定但不在传入列表中
        const isMissing = !isInPassed
        
        // 判断是否已投票
        const hasVoted = votedHouseIds.has(String(houseId))
        
        return {
          id: houseId,
          name: areaInfo + '-' + roomCode,
          area: house.house.houseSize || 0,
          isMissing: isMissing, // 标记为新增的房屋
          hasVoted: hasVoted,   // 标记为已投票的房屋
          rawData: house
        }
      })
      
      // 统计新增房屋数量（未投票的新增房屋）
      const missingCount = this.houseList.filter(h => h.isMissing && !h.hasVoted).length
      const votedMissingCount = this.houseList.filter(h => h.isMissing && h.hasVoted).length
      
      console.log('房屋统计:', {
        total: this.houseList.length,
        missing: this.houseList.filter(h => h.isMissing).length,
        missingUnvoted: missingCount,
        missingVoted: votedMissingCount
      })
      
      if (missingCount > 0) {
        uni.showToast({
          title: `发现${missingCount}套新增房屋待投票`,
          icon: 'none',
          duration: 2000
        })
      } else if (votedMissingCount > 0) {
        uni.showToast({
          title: `所有新增房屋均已投票`,
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 去绑定房屋
    goToBind() {
      uni.navigateTo({
        url: '/pages/bindhouse/index?source=related'
      })
    },
    
    // 去投票
    goToVote() {
      // 标记是从关联房屋页面返回，返回后需要重新投票
     
      
      uni.navigateBack()
    }
  }
}
</script>

<style lang="scss" scoped>
.related-houses-page {
  min-height: 100vh;
  background: linear-gradient(180deg, #E8F0FF 0%, #F5F7FA 400rpx);
  padding: 32rpx;
  padding-bottom: 180rpx;
}
.highlight {
      color: #3C75FA;
      font-weight: 600;
    }
// 顶部信息区
.info-section {
  background: #E8F0FF;
  border-radius: 16rpx;
  padding: 32rpx 24rpx;
  margin-bottom: 32rpx;
  
  .info-text {
    font-size: 28rpx;
    color: #333;
    line-height: 1.6;
    margin-bottom: 16rpx;
    
    
  }
  
  .warning-text {
    font-size: 24rpx;
    color: #666;
    line-height: 1.6;
    margin-bottom: 8rpx;
  }
  
  .tip-text {
    font-size: 24rpx;
    color: #666;
    line-height: 1.6;
  }
}

// 房屋列表区
.house-section {
  background: #fff;
  border-radius: 16rpx;
  padding: 32rpx 24rpx;
  
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24rpx;
    
    .section-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #222;
    }
    
    .bind-btn {
      padding: 8rpx 20rpx;
      background: #fff;
      border: 2rpx solid #3C75FA;
      border-radius: 8rpx;
      
      .bind-text {
        font-size: 24rpx;
        color: #3C75FA;
      }
    }
  }
  
  .house-list {
    .house-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 28rpx 30rpx;
      margin-bottom: 16rpx;
      background: #F8F9FA;
      border-radius: 12rpx;
      border: 2rpx solid #E8E9EB;
      transition: all 0.3s;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      &.missing {
        position: relative;
        background: #FFF9F5;
        border-color: #FFB976;
        
        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          bottom: 0;
          width: 6rpx;
          background: #FF9F43;
          border-radius: 12rpx 0 0 12rpx;
        }
      }
      
      &.voted {
        position: relative;
        background: #F0F9F4;
        border-color: #B3E5C5;
        
        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 0;
          bottom: 0;
          width: 6rpx;
          background: #52C41A;
          border-radius: 12rpx 0 0 12rpx;
        }
      }
      
      .house-info {
        display: flex;
        align-items: center;
        flex: 1;
        
        .house-name {
          font-size: 28rpx;
          color: #333;
          margin-right: 8rpx;
        }
        
        .house-area {
          font-size: 28rpx;
          color: #666;
        }
      }
      
      .house-status {
        display: flex;
        align-items: center;
        gap: 12rpx;
        
        .missing-tag {
          font-size: 22rpx;
          color: #FF9F43;
          background: #FFE8D1;
          padding: 6rpx 16rpx;
          border-radius: 8rpx;
          font-weight: 500;
        }
        
        .voted-tag {
          font-size: 22rpx;
          color: #52C41A;
          background: #D9F7E5;
          padding: 6rpx 16rpx;
          border-radius: 8rpx;
          font-weight: 500;
        }
      }
    }
  }
}

// 底部按钮
.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 32rpx;
  padding-bottom: calc(24rpx + env(safe-area-inset-bottom));
  background: #fff;
  box-shadow: 0 -4rpx 16rpx 0 rgba(0,0,0,0.05);
  
  .action-btn {
    width: 100%;
    height: 88rpx;
    background: linear-gradient(135deg, #4D7CFF 0%, #3C75FA 100%);
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    font-weight: 600;
    color: #fff;
    box-shadow: 0 8rpx 16rpx 0 rgba(60, 117, 250, 0.3);
  }
}
</style>

